const express = require('express');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const userService = require('../services/userService');

var router = express.Router();

router.use('/loginPage.html',async function (req,res,next) {
    // var user = req.cookies['user'];
    var user = req.cookies.user;
    if (user == undefined || user == {}){
        console.log("cookies is null");
        next();
    }else if(user.role == 'admin'){   //admin用户不可以自动登录
        console.log("role admin cannot auto login!");
        next();
    }else {
        //  自动登录-->user角色
        var data = await userService.loginCookie(user);
        if (data.success){
            req.session.user = data.user;
            //  这个过程是从客户端发出的信息
            res.redirect('/views/pages/user1.html');
        }else {
            next();
        }
    }
});
//  对pages里的东西进行控制--> 普通文件夹控制
router.use('/pages',function (req,res,next) {
    console.log('/pages');
    var user = req.session.user;
    if(user == [] || user == {} || user == undefined || user ==''){
        res.redirect('/views/loginPage.html');
    }else {
        next();
    }
});
//  对admin里的东西进行控制
router.use('/admin',function (req,res,next) {
    console.log("/admin");
    var user = req.session.user;
    if(user == [] || user == {} || user == undefined || user ==''){
        res.redirect('/views/loginPage.html');
    }else if(user.role == 'user'){   // user可以自动登录
        res.redirect('/views/loginPage.html');
    }else {
        next();
    }
});
//  在views路由上做登录使用控制
//  要进入pages下面的页面，必须是登录状态，否则全部进入/views/loginPage.html
// router.use('/pages',(req,res,next)=>{
//     var user = req.session['user'];
//     if (user == null || user == {} || user == undefined){
//         res.redirect('/views/loginPage.html');
//     }else {
//         next();
//     }
// })
exports.router = router;